# This code is used to clean picture datasets that crawled on the baidu.image.com
# The dataset covers the kind of smoking people, but it also have manny useful picture
# This code file use the face-recognition frame to clean the dataset

import os
import face_recognition
import cv2
import numpy as np
from tkinter.filedialog import askdirectory


def cv_imread(filePath):
    try:
        cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
        # # imdecode读取的是rgb，如果后续需要opencv处理的话，需要转换成bgr，转换后图片颜色会变化
        # # cv_img=cv2.cvtColor(cv_img,cv2.COLOR_RGB2BGR)
        return cv_img
    except:
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
              "!          This picture can not Open!        !\n"
              "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
              "           !!!!!!!!!!!!!!!!!!!!!!!!           \n"
              "                     !!!!                     \n")
        cv_img = None
        return cv_img


if __name__ == '__main__':
    paths = []
    # imageFiles = []
    dir_with_images = askdirectory(title="classifier the images")
    imageFiles = [x for x in os.listdir(dir_with_images)]
    new_paths = "C:/dataset/CleanedSmoker"
    if not os.path.exists(new_paths):
        os.makedirs(new_paths)
    for i in range(len(imageFiles)):
        middle_path = dir_with_images + "/" + imageFiles[i]
        paths.append(middle_path)
    print(paths)
    print(len(paths))
    n = 0
    # imageFiles = [x for x in os.listdir(paths[i])]
    # print(imageFiles)
    for i in range(len(paths)):
        imageFiles = [x for x in os.listdir(paths[i])]
        print(imageFiles)
        print(len(imageFiles))
        for j in range(len(imageFiles)):
            useful_path = paths[i] + "/" + imageFiles[j]
            print("<<<<<<<<<<<<<<<<<<<", useful_path)
            n += 1
            print(n)
            img = cv_imread(useful_path)
            if img is None:
                break
            # cv2.namedWindow(useful_path, cv2.WINDOW_AUTOSIZE)
            # cv2.imshow(useful_path, img)
            # cv2.waitKey(60)
            # cv2.destroyAllWindows()
            image = face_recognition.load_image_file(useful_path)
            face_locations = face_recognition.face_locations(image)
            print(face_locations)
            if len(face_locations) != 0:
                cv2.namedWindow(useful_path, cv2.WINDOW_AUTOSIZE)
                cv2.imshow(useful_path, image)
                cv2.waitKey(60)
                cv2.destroyAllWindows()
                new_paths = new_paths+"/"+"1912051700"+str(n)+".jpg"
                print(">>>>>>>>>>>>>>>>>>>>", new_paths)
                cv2.imwrite(new_paths, img)
            # my_thread = threading.Thread(target=lock_test, args=(useful_path, new_paths))
            # my_thread.start()
            new_paths = "C:/dataset/CleanedSmoker"
            if not os.path.exists(new_paths):
                os.makedirs(new_paths)






